#!/bin/sh
set -e

# 当前工作目录。拼接绝对路径的时候需要用到这个值。
WORKDIR=$(pwd)

# 如果存在旧的目录和文件，就清理掉
rm -rf *.tar.gz \
    cmake-4.1.2 \
    openssl-3.0.9 \
    ohos-sdk \
    openssl-3.0.9-ohos-arm64 \
    cmake-4.1.2-ohos-arm64

# 准备 ohos-sdk
mkdir ohos-sdk
curl -L -O https://repo.huaweicloud.com/openharmony/os/6.0-Release/ohos-sdk-windows_linux-public.tar.gz
tar -zxf ohos-sdk-windows_linux-public.tar.gz -C ohos-sdk
cd ohos-sdk/linux
unzip -q native-*.zip
cd ../..

# 设置交叉编译所需的环境变量
export OHOS_SDK=${WORKDIR}/ohos-sdk/linux
export AS=${OHOS_SDK}/native/llvm/bin/llvm-as
export CC="${OHOS_SDK}/native/llvm/bin/aarch64-unknown-linux-ohos-clang"
export CXX="${OHOS_SDK}/native/llvm/bin/aarch64-unknown-linux-ohos-clang++"
export LD=${OHOS_SDK}/native/llvm/bin/ld.lld
export STRIP=${OHOS_SDK}/native/llvm/bin/llvm-strip
export RANLIB=${OHOS_SDK}/native/llvm/bin/llvm-ranlib
export OBJDUMP=${OHOS_SDK}/native/llvm/bin/llvm-objdump
export OBJCOPY=${OHOS_SDK}/native/llvm/bin/llvm-objcopy
export NM=${OHOS_SDK}/native/llvm/bin/llvm-nm
export AR=${OHOS_SDK}/native/llvm/bin/llvm-ar

# 编译 openssl
curl -L -O https://github.com/openssl/openssl/releases/download/openssl-3.0.9/openssl-3.0.9.tar.gz
tar -zxf openssl-3.0.9.tar.gz
cd openssl-3.0.9/
./Configure --prefix=${WORKDIR}/openssl-3.0.9-ohos-arm64 linux-aarch64 no-shared
make -j$(nproc)
make install
cd ..

# 准备 cmake 源码
curl -L -O https://github.com/Kitware/CMake/releases/download/v4.1.2/cmake-4.1.2.tar.gz
tar -zxf cmake-4.1.2.tar.gz
cd cmake-4.1.2

# 打补丁，禁用掉 ohos 不支持的 pthread_getaffinity_np 和 pthread_setaffinity_np 接口
patch -p1  < ../0001-disable-cpu-affinity.patch

# 编译 cmake
mkdir build
cd build
cmake .. \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX=${WORKDIR}/cmake-4.1.2-ohos-arm64 \
    -DCMAKE_SYSTEM_NAME=Linux \
    -DCMAKE_SYSTEM_PROCESSOR=aarch64 \
    -DCMAKE_C_COMPILER=$CC \
    -DCMAKE_CXX_COMPILER=$CXX \
    -DOPENSSL_SSL_LIBRARY=${WORKDIR}/openssl-3.0.9-ohos-arm64/lib/libssl.a \
    -DOPENSSL_CRYPTO_LIBRARY=${WORKDIR}/openssl-3.0.9-ohos-arm64/lib/libcrypto.a \
    -DOPENSSL_INCLUDE_DIR=${WORKDIR}/openssl-3.0.9-ohos-arm64/include \
    -DCURL_CA_BUNDLE=/etc/ssl/certs/cacert.pem \
    -DCURL_CA_PATH=/etc/ssl/certs
make -j$(nproc)
make install
cd ../../

# 履行开源义务，把使用的开源软件的 license 全部聚合起来放到制品中
cmake_license=$(cat cmake-4.1.2/LICENSE.rst; echo)
cmake_authors=$(cat cmake-4.1.2/CONTRIBUTORS.rst; echo)
openssl_license=$(cat openssl-3.0.9/LICENSE.txt; echo)
openssl_authors=$(cat openssl-3.0.9/AUTHORS.md; echo)
printf '%s\n' "$(cat <<EOF
This document describes the licenses of all software distributed with the
bundled application.
==========================================================================

cmake
=============
==license==
$cmake_license
==authors==
$cmake_authors

openssl
=============
==license==
$openssl_license
==authors==
$openssl_authors
EOF
)" > cmake-4.1.2-ohos-arm64/licenses.txt

# 打包最终产物
tar -zcf cmake-4.1.2-ohos-arm64.tar.gz cmake-4.1.2-ohos-arm64
